<template>
  <ContentContainer
    :show-pagination="false"
    :show-footer="false"
    :refresh="false">
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      layout="vertical"
      class="anti-form"
      scroll-to-first-error>
      <div class="weight-label">防盗链配置</div>
      <a-form-item
        field="hotlink_protection.status"
        hide-label
        hide-asterisk
        asterisk-position="end"
        required>
        <a-radio-group v-model="form.hotlink_protection.status">
          <a-radio :value="2">关闭</a-radio>
          <a-radio :value="1">开启</a-radio>
        </a-radio-group>
      </a-form-item>
      <section v-if="form.hotlink_protection.status === 1" class="mb-6">
        <a-form-item
          field="hotlink_protection.empty_referer_allow_status"
          label="空 Referer 访问"
          hide-asterisk
          asterisk-position="end"
          required>
          <a-radio-group
            v-model="form.hotlink_protection.empty_referer_allow_status">
            <a-radio :value="1">允许</a-radio>
            <a-radio :value="2">不允许</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          field="hotlink_protection.mode"
          label="模式"
          hide-asterisk
          asterisk-position="end"
          class="!mb-0"
          required>
          <a-radio-group v-model="form.hotlink_protection.mode">
            <a-radio :value="1">黑名单</a-radio>
            <a-radio :value="2">白名单</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          field="hotlink_protection.file_content"
          hide-label
          hide-asterisk
          class="mt-2"
          required>
          <basic-textarea
            ref="urlRef"
            v-model:value="form.hotlink_protection.file_content"
            word-limit-type="multiple-line"
            :autoSize="true"
            placeholder="请输入 IP 地址/域名，一行一个，支持泛域名" />
        </a-form-item>
        <a-form-item
          field="hotlink_protection.file_type"
          label="文件类型"
          hide-asterisk
          asterisk-position="end"
          required>
          <a-radio-group v-model="form.hotlink_protection.file_type">
            <a-radio :value="1">所有</a-radio>
            <a-radio :value="2">文件后缀</a-radio>
            <a-radio :value="3">文件路径</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          v-if="form.hotlink_protection.file_type === 2"
          field="hotlink_protection.file_extension"
          label="匹配内容"
          hide-asterisk
          required>
          <basic-textarea
            v-model:value="form.hotlink_protection.file_extension"
            :autoSize="true"
            placeholder="请输入文件后缀，多个值用英文逗号隔开，区分大小写" />
        </a-form-item>
        <a-form-item
          v-if="form.hotlink_protection.file_type === 3"
          field="hotlink_protection.file_path"
          label="匹配内容"
          hide-asterisk
          required>
          <basic-textarea
            v-model:value="form.hotlink_protection.file_path"
            word-limit-type="multiple-line"
            :autoSize="true"
            placeholder="请输入模糊匹配的文件路径，一行一个" />
        </a-form-item>
      </section>
      <a-button
        type="primary"
        class="w-fit mb-6"
        :loading="saveLoading"
        @click="handleSave"
        >保存配置</a-button
      >
    </a-form>
  </ContentContainer>
</template>
<script lang="ts" setup>
import {
  getApiSiteHotlinkProtectionApi,
  updateApiSiteHotlinkProtectionApi
} from '@/apis/modules/site/site'
import { cloneDeep, omit } from 'lodash-es'
const route = useRoute()
const id = computed(() => route.params.id as string)
const urlRef = ref()
const formRef = ref()
const form = ref({
  hotlink_protection: {
    status: 2,
    mode: 1,
    empty_referer_allow_status: 1,
    file_content: '',
    file_type: 1,
    file_extension: '',
    file_path: '',
    referer_host_list: [],
    file_suffix_list: [],
    file_path_list: []
  }
})
const rules = {
  'hotlink_protection.browser_cache_time': [
    { required: true, message: '请输入浏览器缓存时间' }
  ],
  'hotlink_protection.index_cache_time': [
    { required: true, message: '请输入过期时间' }
  ],
  region_id: [{ required: true, message: '请选择区域' }],
  protocol: [{ required: true, message: '请选择回源协议' }],
  'hotlink_protection.file_content': [
    { required: true, message: '请输入 IP 地址/域名' },
    {
      validator(_value, callback) {
        if (urlRef.value.urls.length > 400) {
          callback('超过最大限制条数')
        }
        callback(
          validateHandler(urlRef.value.urls, (data) => {
            const error = '域名格式错误'
            if (data.startsWith('*.')) {
              data = data.substring(2, data.length - 1)
            }
            return regExpValidateHandler(data, regexpMap.ipv4OrDomain, error)
          })
        )
      }
    }
  ],
  'hotlink_protection.file_extension': [
    { required: true, message: '请输入文件后缀' },
    {
      validator: validateSuffix
    }
  ],
  'hotlink_protection.file_path': [
    { required: true, message: '请输入文件路径' },
    {
      validator(value, callback) {
        const reg = /^\/(?:[^/]+(\/)?)*$/
        const paths = value.split('\n').filter(Boolean)
        callback(
          validateHandler(paths, (data) => {
            // const index = paths.findIndex((item) => data === item)
            // const error = `第${index + 1}行路径格式不正确`
            const error = `路径格式不正确`
            return regExpValidateHandler(data, reg, error)
          })
        )
      }
    }
  ]
}
//缓存配置
const { request } = useRequest(getApiSiteHotlinkProtectionApi, {
  auto: false,
  params: { id: id.value },
  success: (res) => {
    Object.assign(form.value, res)
    form.value.hotlink_protection.file_content = textTransfer(
      form.value.hotlink_protection.referer_host_list ?? []
    ) as string
    if (form.value.hotlink_protection.file_type === 2) {
      form.value.hotlink_protection.file_extension =
        form.value.hotlink_protection.file_suffix_list?.join(',')
    } else if (form.value.hotlink_protection.file_type === 3) {
      form.value.hotlink_protection.file_path = textTransfer(
        form.value.hotlink_protection?.file_path_list ?? []
      ) as string
    }
  }
})

const saveLoading = ref(false)
const textTransfer = (value: string | string[]) => {
  if (!Array.isArray(value)) return value?.split('\n').filter(Boolean)
  return value.join('\n')
}
const handleSave = async () => {
  const err = await formRef.value?.validate()
  if (err) return
  saveLoading.value = true
  const data = cloneDeep(form.value)
  data.hotlink_protection.referer_host_list = textTransfer(
    form.value.hotlink_protection.file_content
  )
  if (data.hotlink_protection.file_type === 1) {
    data.hotlink_protection.file_suffix_list = null
    data.hotlink_protection.file_path_list = null
  } else if (data.hotlink_protection.file_type === 2) {
    data.hotlink_protection.file_suffix_list =
      form.value.hotlink_protection.file_extension.split(',')
  } else {
    data.hotlink_protection.file_path_list = textTransfer(
      form.value.hotlink_protection.file_path
    )
  }
  data.hotlink_protection = omit(data.hotlink_protection, [
    'file_content',
    'file_extension',
    'file_path'
  ])
  updateApiSiteHotlinkProtectionApi({
    id: id.value,
    ...data
  })
    .then(() => {
      ToastUtils.success('操作成功')
      request({ id: id.value })
    })
    .finally(() => (saveLoading.value = false))
}
watchEffect(() => {
  request({ id: id.value })
})
</script>

<style lang="less" scoped>
.weight-label {
  @apply text-sm/22px font-700 text-1 mb-6;
}
.normal-label {
  @apply text-sm/22px text-2;
}
.sub-label {
  @apply text-xs/5 text-5;
}
.anti-form {
  :deep(.arco-form-item-wrapper-col) {
    @apply !min-h-22px;
    .arco-form-item-content {
      @apply !min-h-22px;
      &:has(.arco-radio-group) {
        @apply !min-h-22px;
      }
    }
  }
}
</style>
